package org.openwebtop.sunshine.action.user;

import java.util.Calendar;
import java.util.GregorianCalendar;

import org.apache.commons.lang.StringUtils;
import org.openwebtop.sunshine.bo.UserBO;
import org.openwebtop.sunshine.constants.GlobalConstants;
import org.openwebtop.sunshine.constants.GlobalForwards;
import org.openwebtop.sunshine.model.GlobalMessage;
import org.openwebtop.sunshine.model.User;
import org.openwebtop.sunshine.user.UserContext;
import org.openwebtop.sunshine.user.UserContextAware;
import org.openwebtop.sunshine.util.GlobalContext;

import com.opensymphony.xwork.ActionSupport;

public class LoginAction implements UserContextAware {
	private UserContext userContext;
	private UserBO userBO;

	// Params
	private String userid;
	private String password;

	// Getter
	private GlobalMessage globalMessage;

	public String execute() throws Exception {
		if (userContext.isLogin()) {
			this.globalMessage = new GlobalMessage();
			globalMessage.setTitle("You are already Logged in.");
			globalMessage.setMessage(null);

			return GlobalForwards.GLOBAL_MESSAGE;
		}

		return ActionSupport.SUCCESS;
	}

	public String loginExec() throws Exception {
		if (StringUtils.isNotBlank(userid) && StringUtils.isNotBlank(password)) {
			final User user = userBO.getUser(userid, password);

			if (user != null) {
				final UserContext userContext = new UserContext(user, true);

				final Calendar calendar = new GregorianCalendar();
				userContext.setLastAccessDate(calendar.getTime());

				GlobalContext.setAttribute(GlobalConstants.USER_CONTEXT_KEY, userContext);

				return ActionSupport.SUCCESS;
			}
		}

		this.globalMessage = new GlobalMessage();
		globalMessage.setTitle("Login Failure");
		globalMessage.setMessage("invalid login data");

		return GlobalForwards.GLOBAL_MESSAGE;
	}

	@Override
	public void setUserContext(UserContext userContext) {
		this.userContext = userContext;
	}

	public void setUserBO(UserBO userBO) {
		this.userBO = userBO;
	}

	public void setUserid(String userid) {
		this.userid = userid;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public GlobalMessage getGlobalMessage() {
		return globalMessage;
	}

}
